package com.nizi.wordoperate.controller;

import com.nizi.wordoperate.utils.DownLoadUtil;
import com.nizi.wordoperate.utils.GenerateWord;
import com.nizi.wordoperate.utils.GenerateWordDocx;
import com.nizi.wordoperate.utils.ReadExcelXlsx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/api/all")
public class AllController {

    private static final Logger logger = LoggerFactory.getLogger(AllController.class);
    private static String key = "file";

    @Value("${workDir}")
    private String workDir;


    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public void uploadFile(HttpServletRequest request, HttpServletResponse response,String token) {
        List<File> downLoadFiles = new ArrayList<>();
        String fileAbsolutePath = "";
        try {
            //写本地文档
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(key);
            assert multipartFile != null;
            String fileName = multipartFile.getOriginalFilename();
            //文件名称加随机数处理，避免重名
            assert fileName != null;
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() % 1000 + fileName.substring(fileName.lastIndexOf("."));
            fileAbsolutePath = getPath("upload/") + fileName;
            logger.info(fileAbsolutePath);
            writeFile(fileAbsolutePath, multipartFile.getBytes());
            List<Map<String, Object>> list = ReadExcelXlsx.ReadExcelFinal(fileAbsolutePath);
            list.forEach(map -> {
                        String downLoadFileName = getPath("downLoad/") + map.get("Name") + "_" + map.get("Id").toString().substring(map.get("Id").toString().length()-4) + ".docx";
                        try {
                            GenerateWordDocx.GenerateDocx(getPath("contract/") + "contract.docx", map, downLoadFileName);
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.info(e.getMessage());
                        }
                        downLoadFiles.add(new File(downLoadFileName));
                    }
            );
            DownLoadUtil.downLoadFiles(downLoadFiles, response, getPath("tempFile/") + "tempFile_"+token+".zip");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }

    }

    //通过spring的配置文件，将文件上传到预先准备的文件夹下
    private String getPath(String dicName) {
        return workDir+dicName;
    }

    public static void writeFile(String fileAbsolutePath, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileAbsolutePath);
        fos.write(content);
        fos.close();
    }

}
